<?php
/**
 * Created by PhpStorm.
 * User: liang
 * Date: 2017/4/30
 * Time: 22:35
 */

namespace App\Admin\Controllers;


use Admin;
use App\Http\Controllers\Controller;
use App\Models\EditorImages;
use Encore\Admin\Form\Field\UploadField;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;


class FileController extends Controller
{

    use UploadField;

    public function delImage(Request $request){
        $id = $request->input("id");

        $img = EditorImages::findOrFail($id);

        $this->initStorage();
        $state = $this->storage->delete($img->img_name);
        if($state){
            $img->delete();
            return response()->json(['status_code'=>200,'message'=>'删除成功']);
        }else{
            return response()->json(['status_code'=>0,'message'=>'删除失败']);
        }


    }

    public function uploadImage(Request $request)
    {
        $file = $request->file($request->input("name"));
        $pic_style = $request->input("pic_style");
        if ($file->isValid()) {
            $this->initStorage();
            //$target = "images/" . md5(uniqid()) . '.' . $file->guessExtension();
            $target = "images/" . $file->getClientOriginalName();
            $re = $this->storage->put($target, file_get_contents($file->getRealPath()));
            if ($re) {
                if (URL::isValidUrl($target)) {
                    return $target;
                }
                if ($file->guessExtension() == 'gif') {
                    $pic_style = '';
                }

                EditorImages::create(
                    [
                        'user_id' => Admin::user()->id,
                        'img_name'=>$target
                    ]
                );

                return rtrim(config('admin.upload.host'), '/') . '/' . trim($target, '/') . $pic_style;
            } else {
                exit("error|上传失败");
            }

        } else {
            exit("error|服务器端错误");
        }
    }
}